/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.ipti.br.tag.util;

import org.ipti.br.tag.bo.DeletesBO;
import org.ipti.br.tag.entity.AbstractEntity;
import org.ipti.br.tag.entity.Deletes;
import java.io.Serializable;
import java.util.Calendar;
import javax.inject.Inject;
import javax.persistence.PrePersist;
import javax.persistence.PreRemove;
import javax.persistence.PreUpdate;

/**
 *
 * @author luancorumba
 */
public class EntityJPAListener extends NonBeanInjection<Object> implements Serializable{
    
    @Inject private Application app;
    @Inject private DeletesBO deletesBO;
    
    @PrePersist
    public void initPersist(AbstractEntity abstractEntity){
        if(abstractEntity.getId() == null){
            abstractEntity.generateHash();
        }
        
        abstractEntity.setLastModified(Calendar.getInstance());
        
        if(abstractEntity.getSerialNumber() == null) {
//            initApp();
            abstractEntity.setSerialNumber(app.getId());
        }
    }
    
    @PreUpdate
    public void initUpdate(AbstractEntity abstractEntity){
        if(!abstractEntity.isSyncing()){
//            initApp();
            abstractEntity.setSerialNumber(app.getId());
        }
        abstractEntity.setLastModified(Calendar.getInstance());
    }
    
    @PreRemove
    public void recordDelete(AbstractEntity abstractEntity){
//        initApp();
//        initDelete();
        Deletes d = new Deletes();
        d.setTargetTable(abstractEntity.getClass().getSimpleName().toLowerCase());
        d.setHashID(abstractEntity.getId());
        d.setOccurredDate(Calendar.getInstance());
        d.setSerialNumber(app.getId());
        deletesBO.create(d);
    }
    
    public void initApp(){
        app = (Application) getBean(Application.class.getSimpleName());
    }
    
    public void initDelete(){
        deletesBO = (DeletesBO) getBean(DeletesBO.class.getSimpleName());
    }
}
